package com.yxt.shecaiyun.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxt.shecaiyun.common.PageResult;
import com.yxt.shecaiyun.dto.userDto.UserQueryDTO;
import com.yxt.shecaiyun.dto.userDto.UserUpdateDTO;
import com.yxt.shecaiyun.entity.User;
import com.yxt.shecaiyun.mapper.UserMapper;
import com.yxt.shecaiyun.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor  // Lombok自动注入依赖
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
//    @Autowired
//    private UserService userService;
    @Override
    public boolean existsByAccount(String account) {
        return lambdaQuery()
                .eq(User::getAccount, account)
                .exists();
    }

    @Override
    public boolean existsByUserID(String userNumber) {
        return lambdaQuery()
                .eq(User::getNumber, userNumber)
                .exists();
    }

    @Override
    public User findByAccount(String account) {
        return lambdaQuery()
                .eq(User::getAccount, account)
                .one();
    }
    private final UserMapper userMapper;

    @Override
    public PageResult<User> getUserPage(UserQueryDTO query) {
        // 1. 构建分页参数（MyBatis Plus分页对象）
        Page<User> page = new Page<>(query.getPage(), query.getPageSize());

        // 2. 构建查询条件（使用QueryWrapper）
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(!StringUtils.isEmpty(query.getAccount()), User::getAccount, query.getAccount()) // 账号模糊查询
                .eq(!StringUtils.isEmpty(query.getMajor()), User::getMajor, query.getMajor())         // 专业精确匹配
                .eq(query.getStatus() != null, User::getActive, query.getStatus())                  // 状态筛选
                .orderByDesc(User::getId);                                                           // 按ID倒序

        // 3. 执行分页查询
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        // 4. 封装返回结果
        return new PageResult<>(
                userPage.getTotal(),
                userPage.getRecords(),
                userPage.getCurrent(),
                userPage.getSize()
        );
    }
    @Override
    public void updateUser(User user, UserUpdateDTO dto) {
        // 将 dto 的字段复制到 user 对象
        BeanUtils.copyProperties(dto, user);
        this.updateById(user);
    }

}